package com.hyl.config.security;

import com.hyl.entity.Permission;
import com.hyl.entity.User;
import com.hyl.service.PermissionService;
import com.hyl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2023/6/20 13:33
 **/
@Component
public class CustomerUserDetailsService implements UserDetailsService {

	@Resource
	private UserService userService;

	@Resource
	private PermissionService permissionService;

	@Override
	public UserDetails loadUserByUsername(String username) throws
			UsernameNotFoundException {
		//调用根据用户名查询用户信息的方法
		User user = userService.findUserByUserName(username);
		//如果对象为空，则认证失败
		if (user == null) {
			throw new UsernameNotFoundException("用户名或密码错误!");
		}
		List<Permission> permissionList = permissionService.findPermissionListByUserId(user.getId());
		//设置菜单列表
		user.setPermissionList(permissionList);
		//获取编码权限
		List<String> collect = permissionList.stream()
				.filter(item->item!=null)
				.map(item->item.getCode()).filter(item->item!=null)
				.collect(Collectors.toList());
		//转换铖数据
		String[] Strings = collect.toArray(new String[collect.size()]);
		//设置权限列表
		List<GrantedAuthority> authoritieList = AuthorityUtils.createAuthorityList(Strings);
		user.setAuthorities(authoritieList);
		return user;
	}
}